package com.nerve.cloudoffice.web.intercept;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.nerve.util.RequestUtil;

import com.nerve.cloudoffice.common.Const;
import com.nerve.cloudoffice.common.SessionUtil;
import com.nerve.cloudoffice.domain.User;
import com.nerve.cloudoffice.service.ServiceExceptions;
import com.nerve.cloudoffice.service.UserService;
import com.nerve.cloudoffice.service.impl.UserServiceImpl;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @project: cloudOffice
 * @file: LoginInterceptor.java
 * @package: com.nerve.cloudoffice.web.intercept
 * @description:
 *	登录拦截器
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: 2013-8-4
 * @change log:
 */
@SuppressWarnings("serial")
public final class LoginInterceptor extends AbstractInterceptor {
	
	private UserService service = new UserServiceImpl();
	
	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		
		User user = SessionUtil.getLoginUser();
		
		if(user != null){
			return arg0.invoke();
		}
		
		/*
		 * 如果session中的user为空
		 * 那么尝试从request中得到 Login_name , login_pass两个参数
		 * 如果有，就用这两个参数去登录
		 */
		String name = RequestUtil.getString(request, Const.LOGIN_NAME);
		String pass = RequestUtil.getString(request, Const.LOGIN_PASS);
		
		if(name != null && pass != null){
			try{
				name = new String(name.getBytes("ISO-8859-1"), "utf-8");
				user = service.login(name, pass);
				
				if(user != null){
					SessionUtil.put(request, Const.LOGIN_USER, user);
					
					return arg0.invoke();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		//到了这里，那么就是没有登录啦
		HttpServletResponse response = ServletActionContext.getResponse();
		
		SessionUtil.jsonAfterIntercept(response, ServiceExceptions.NO_LOGIN);
		System.out.println("login interceptor!!!!!!");
		return null;
	}

}